#include "files.h"
int open()
{
	printf("open\n");
	return 0;
}
int write()
{
	printf("write\n");
	return 0;
}
int read()
{
	printf("read\n");
	return 0;

}
int close()
{
	printf("close\n");
	return 0;

}

MYFILE* mfopen(const char* filename, const char* mod)
{
	assert(filename && mod);
	int sz = sizeof(MYFILE);
	MYFILE* newfile = malloc(sizeof(MYFILE));
	if (newfile == NULL)
	{
		perror("mfopen->malloc::");
		exit(1);
	}
	memset(newfile, 0, sizeof(MYFILE));
	newfile->fileno = -1;
	newfile->cap = FILE_SIZE;
	if (strcmp(mod, "r") == 0)
	{
		//newfile->openmod = _READONLY;
		newfile->fileno = open(filename, O_RDONLY);
	}
	else if (strcmp(mod, "w") == 0)
	{
		//newfile->openmod = _WRITEONLY;
		newfile->fileno = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
	}
	else if (strcmp(mod, "a") == 0)
	{
		//newfile->openmod = _APPEND;
		newfile->fileno = open(filename, O_WRONLY | O_CREAT | O_APPEND, 0666);
	}
	if (newfile->fileno == -1)
	{
		free(newfile);
		newfile = NULL;
		perror("mfopen->open::");
		exit(1);
	}
	return newfile;
}
int mfwrite(void* ptr, int num, MYFILE* stream)
{
	assert(ptr && stream);
	int len = strlen(ptr);
	if (num > len)
	{
		num = len;
	}
	while (num > stream->cap)
	{
		memcpy(stream->outbuffer, ptr, stream->cap);
		stream->size = stream->cap;
		stream->flushmod = 3;
		mfflush(stream);
		num -= stream->cap;
		printf("%d %d\n", num, stream->cap);
	}
	if (num > 0)
	{
		memcpy(stream->outbuffer, ptr, num);
		stream->size = num;
		mfflush(stream);
	}
	return 0;
}

int mfread(const void* ptr, int num, MYFILE* stream)
{
	assert(ptr && stream);
	read(stream->fileno, num, stream->fileno);
	return 0;
}
void mfflush(MYFILE* stream)
{
	assert(stream);
	write(stream->fileno, stream->outbuffer, stream->size);
	printf("%s", stream->outbuffer);
	memset(stream->outbuffer, 0, FILE_SIZE);
	stream->size = 0;
}
void mfclose(MYFILE* stream)
{
	assert(stream);
	mfflush(stream);
	close(stream->fileno);
	free(stream);
	stream = NULL;
}
